﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace MCorder.control
{
    public class DataSaver
    {
        
        private FileStream m_FS0 = null;
        private StreamWriter m_SW0 = null;
        public  DataSaver(string fileName,string backup_file_path, bool openExtern, string fileName1)
        {
            if (openExtern == false)
            {
                if (false == Directory.Exists("data"))
                {
                    Directory.CreateDirectory("data");
                }

                string dataFile = "data/" + fileName + ".txt";
                m_FS0 = new FileStream(dataFile, FileMode.Create, FileAccess.Write);
                m_SW0 = new StreamWriter(m_FS0);
            }
            else
            {
                m_FS0 = new FileStream(backup_file_path, FileMode.Append);

                m_SW0 = new StreamWriter(m_FS0);
            }
            m_SW0.WriteLine("FileName:\t" + fileName1);
            m_SW0.Flush();
        }
        ~DataSaver()
        {
        }
        private static int dataCount = 0;
        System.DateTime startTime, nowtime;
        public void SaveData(DevDataSet ds)
        {
            if (m_FS0 == null) return;
            if (m_SW0 == null) return;
            dataCount++;

          //  nowtime = System.DateTime.Now;
           // long t = (nowtime.Ticks - startTime.Ticks) / 10000;  //除10000调整为ms   

            string lineContent = dataCount.ToString() + "\t";
            lineContent += (ds.pos).ToString("0.000000") + "\t";

            lineContent += ds.cur.ToString("0.0000000") + "\t";

            //  lineContent +=ds.speed.ToString("0.000") + "\t";

            lineContent += ds.voltage.ToString("0.0000000");


            m_SW0.WriteLine(lineContent);
            m_SW0.Flush();
        }

        public void SaveHeader(float scalar,double baseCur,double speed)
        {
            if (m_FS0 == null) return;
            if (m_SW0 == null) return;
            dataCount = 0;
            m_SW0.WriteLine("Start Time:\t" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"));

            m_SW0.WriteLine("Coefficient(V/A):\t" + scalar.ToString("0.00000"));
            m_SW0.WriteLine("Speed(m/s):\t" + speed.ToString("0.00"));

            m_SW0.WriteLine("Base Current(A):\t " + baseCur.ToString());

            string headerLine = "Timems\tPosition(m)\tCurrent(A)";
            m_SW0.WriteLine(headerLine);
            m_SW0.Flush();

            startTime =DateTime.Now;

        }

        public void SaveEnd()
        {
            if (m_FS0 == null) return;
            if (m_SW0 == null) return;
            m_SW0.WriteLine("Stop Time:\t" + DateTime.Now.ToString("yyyyMMdd-HH-mm-ss"));
            m_SW0.Flush();
            dataCount = 0;
        }


    }
}
